package com.wyl.bluetoothapp

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.wyl.bluetoothapp.util.LogUtil
import kotlinx.android.synthetic.main.activity_main.*

/**
Android蓝牙开发流程实践
开启 扫描 配对 连接 通信
 */
class MainActivity : AppCompatActivity() {
    private val viewModel by viewModels<BlueToothViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        checkPermission()

        button.setOnClickListener {
            viewModel.start()
        }
        button2.setOnClickListener {
            viewModel.cancel()
        }
        viewModel.att.observe(this, Observer {
            LogUtil.d("--attention:$it")
            tvAtt.text = it.toString()
        })
        viewModel.signal.observe(this, Observer {
            LogUtil.d("--signal:$it")
            tvSignal.text = it.toString()
        })
        viewModel.connResult.observe(this, Observer {
            tvState.text = it
        })
        tvState.text = "未连接"
    }

    /* 解决兼容性问题，6.0以上使用新的API*/
    private val MY_PERMISSION_ACCESS_COARSE_LOCATION = 11
    private val MY_PERMISSION_ACCESS_FINE_LOCATION = 12

    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                    MY_PERMISSION_ACCESS_COARSE_LOCATION
                )
                Log.e("11111", "ACCESS_COARSE_LOCATION")
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                    MY_PERMISSION_ACCESS_FINE_LOCATION
                )
                Log.e("11111", "ACCESS_FINE_LOCATION")
            }
        }
    }


}
